package edu.suda.xsap.service.impl;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import edu.suda.xsap.entity.Employee;
import edu.suda.xsap.mapper.LoginMapper;
import edu.suda.xsap.service.LoginService;
import edu.suda.xsapadminutils.common.Result;
import edu.suda.xsapadminvo.EmployeeVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    private String text;

    @Override
    public Result login(EmployeeVO employeeVO) {
        String  captcha = employeeVO.getCaptcha().toLowerCase();
        if (captcha.equals(text)) {
            log.debug("==>验证码正确");
            Employee nameAndPassword = loginMapper.findByNameAndPassword(employeeVO.getName(), employeeVO.getPassword());
            if (nameAndPassword != null) {
                return Result.success("登录成功", nameAndPassword);
            } else {
                return Result.failure("用户名或密码错误");
            }
        } else {
            return Result.failure("验证码错误");
        }

    }

    @Override
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.debug("==>生成验证码，指定响应头");
        // 指定响应头
        setHeader(response);
        // 生成验证码对象， 三个参数分别是宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);
        //设置验证码的字符类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        // 设置内置字体
        captcha.setCharType(Captcha.FONT_1);
        log.debug("==>验证码的宽为{},高为{},位数是：{}", 130, 48, 4);
        text = captcha.text().toLowerCase();
        log.debug("==> 本次验证码:{}", text);
        //验证码存入session
        request.getSession().setAttribute("verifyCode",text);
        //输出图片流
        captcha.out(response.getOutputStream());
    }

    @Override
    public void setHeader(HttpServletResponse response) {
        response.setHeader("Cache-Control","no-store");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/gif");
    }

    @Override
    public Result register(EmployeeVO employeeVO) {
        loginMapper.save(employeeVO);
        return Result.success("注册成功");
    }


}
